using System;
using System.Collections.Generic;
using System.Text;
using TTDotNet.Util;
using TTDotNet.Engine.Industries;
using Microsoft.DirectX;
using System.Runtime.InteropServices;

namespace TTDotNet.Engine.ThreeDEngine
{
    public class MeshManager
    {
        private Dictionary<string, List<AJMeshH>> meshes;

        public MeshManager()
        {
            meshes = new Dictionary<string, List<AJMeshH>>();
        }

        public InstancedMesh CreateMesh(string meshPath, Vector3 position, Vector3 rotation,  ObjectType type)
        {
            AJMeshH mesh;
            Guid iID = Guid.Empty;

            if (meshes.ContainsKey(meshPath))
            {
                InstancedMesh im = AlreadyExists(meshPath, position, rotation, type);
                mesh = im.Mesh;
                iID = im.GUID;
            }
            else
            {
                meshes[meshPath] = new List<AJMeshH>();
                mesh = new AJMeshH(meshPath, type);
                meshes[meshPath].Add(mesh);
                
                iID = mesh.AddNewInstance(position, rotation);
            }

            return new InstancedMesh(mesh, iID);
        }

        private InstancedMesh AlreadyExists(string meshPath, Vector3 position, Vector3 rotation, ObjectType type) 
        {
            List<AJMeshH> list = meshes[meshPath];

            AJMeshH mesh = list[list.Count - 1];
            Guid iID = Guid.Empty;

            if (position != null)
            {
                iID = mesh.AddNewInstance(position, rotation);
            }

            return new InstancedMesh(mesh, iID);
        }

    }
}
